<template>
  <div v-loading.fullscreen="loading">
    <el-table
      border
      :data="(sourceHouseConfig.length && sourceHouseConfig) || houseImages"
      style="width: 100%; margin-top: 16px"
      :header-cell-style="{ background: '#EDF6FF' }"
    >
      <el-table-column prop="title" label="图片类型" width="100"></el-table-column>
      <el-table-column label="图片" :width="0">
        <template #default="{ row }">
          <div v-if="row.draggable" class="d-flex ai-center">
            <div class="tips-first" v-if="imageVO[row.key].length">封面图</div>
            <div>默认第一张室内图为封面图，拖拽图片可以移动位置。</div>
          </div>
          <div class="d-flex ai-center flex-wrap">
            <template v-if="row.draggable">
              <draggable
                class="list-group"
                v-model="imageVO[row.key]"
                :move="onMove"
                @start="isDragging = true"
                @end="isDragging = false"
              >
                <transition-group name="flip-list">
                  <div class="list-group-item" v-for="element in imageVO[row.key]" :key="element.fileId">
                    <com-img-item
                      :model="element"
                      :srcList="getSrcList"
                      :isDragging="isDragging"
                      @onremove="handleRemoveImg"
                      @onmodelupdate="handleModelUpdate"
                      @onmove="handleMove"
                    ></com-img-item>
                  </div>
                </transition-group>
              </draggable>
            </template>
            <template v-else>
              <com-img-item
                v-for="item in imageVO[row.key]"
                :model="item"
                :key="item.id"
                :srcList="getSrcList"
                @onremove="handleRemoveImg"
                @onmove="handleMove"
              ></com-img-item>
            </template>
          </div>
          <div>{{ row.tips }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <template v-for="item in row.options">
            <div :key="item.title">
              <el-upload
                v-if="item.option == 'upload'"
                list-type="text"
                :action="uploadImgUrl"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload(row)"
                :on-success="handleSuccess(row)"
                :multiple="true"
                :data="{
                  filetype: '房源图片',
                  app: 'shulan',
                  module: '2',
                  sourceKey: '1',
                }"
              >
                <el-button style="width: 90px;"  size="small" type="primary">上传图片</el-button>
              </el-upload>

              <el-button
                v-if="item.option == 'add' && btnShow(row)"
                style="margin-top: 10px; width: 90px;"
                size="small"
                type="primary"
                plain
                @click="handleAddImg(row)"
                >{{ item.text }}</el-button >

              <el-button
                v-if="item.option == 'watermark'"
                style="margin-top: 10px; width: 90px;"
                size="small"
                type="primary"
                plain
                @click="watermarkPopVisible = true"
                >{{ item.text }}</el-button>
            </div>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <dialog-update-img
      v-if="dialogUpdateImgVisible"
      @ontoggle="handleToggleDialog"
      @onsaveimg="handleSaveImg"
      :tag-code="tagCode"
      :houDelId="houDelId"
      :buildSize="houDelVO.buildSize"
    ></dialog-update-img>

    <dialog-water-mark
      v-if="watermarkPopVisible"
      :houDelId="houDelId"
      @onclose="handleCloseWaterMark"
    ></dialog-water-mark>
  </div>
</template>

<script>
import comImgItem from "./com-img-item";
import DialogUpdateImg from "../dialog/dialog-update-img";
import draggable from "vuedraggable";
import DialogWaterMark from "@/views/house/dialog/dialog-water-mark";

import { houseImages } from "@/config/house/houseDetailConfig";
import { debounce, measureImageInvalid, uniqueComplex } from "@/utils/utilsNew";
import { menuHandler } from "@/handler/menuHandler";
import { VR_COMPOUND_ADD } from "@/config/menuId";
import { getHouseInfo, submitVrTask, updateImage } from "@/api/user";
import { mapGetters } from "vuex";

// imageVO: {
//   houseTypeList: [], //房型图
//   indoorList: [], //室内图
//   circumList: [], //小区图
// },
export default {
  components: {
    draggable,
    comImgItem,
    DialogUpdateImg,
    DialogWaterMark,
  },
  props: {
    sourceHouseConfig: {
      type: Array,
      default() {
        return [];
      },
    },
    // 接口的原始数据
    houImageVO: Array,
    // 自定义的数据格式
    imageVO: {
      type: Object,
      default() {
        return {};
      }
    },
    houDelId: {
      type: String,
      default: "",
    },
    isVrHouse: {
      type: Boolean,
      default: false,
    },
    houDelVO: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    this.uploadedImagesList = []; //上传过的图片名称列表

    return {
      loading: false,
      isDragging: false,
      houseImages: Object.freeze(houseImages),
      dialogUpdateImgVisible: false,
      tagCode: "",
      watermarkPopVisible: false,
    };
  },
  computed: {
    ...mapGetters(["sessionUser"]),
    btnShow() {
      return function(row) {
        if (row.tagCode == "huxingtu") {
          return true;
        } else {
          return this.isVrHouse;
        }
      };
    },
    getSrcList({houImageVO}) {
      return houImageVO.map((v) => v.url)
    }
  },
  watch: {
    houImageVO: {
      handler(newVal) {
        if (newVal && newVal.length) {
          this.renderImages(newVal);
        }
      },
      immediate: true,
    },
  },
  created() {
    this.handleExceed = debounce(this.handleExceed.bind(this));
  },
  methods: {
    handleCloseWaterMark() {
      this.watermarkPopVisible = false
      this.$emit('reload')
    },

    renderImages(vo) {
      const { imageVO } = this;
      vo = uniqueComplex(vo, (item) => item.url);
      imageVO.houseTypeList = [];
      imageVO.indoorList = [];
      imageVO.circumList = [];
      vo.forEach((item, i) => {
        item.invalid = false;
        item.fixed = false;

        let config = houseImages.find((innerItem) => {
          return innerItem.tagCode == item.tagCode;
        });
        config = config || houseImages[1];
        item.selectAble = item.tagCode != "huxingtu" && item.tagCode != "xiaoqu";

        let index = this.imageVO[config.key].push(item);

        measureImageInvalid(item.url, config.minWidth, config.minHeight).catch(() => {
          item.invalid = true;
          this.$set(this.imageVO[config.key], index - 1, item);
        });
      });
    },

    handleToggleDialog(v) {
      this.dialogUpdateImgVisible = v;
    },
    handleSaveImg(tagCode, newValue) {
      // console.log('save', v);
      if (tagCode == "huxingtu") {
        this.imageVO.houseTypeList = newValue;
      } else {
        this.imageVO.indoorList = newValue;
      }

      this.submitImage().then(() => {
        this.$message.success("图片保存成功！");
      });
    },
    async handleAddImg(row) {
      if (row.tagCode == "huxingtu") {
        if (!this.houDelVO.buildSize) {
          return this.$message.error("户型图匹配需要补充建筑面积！");
        }

        this.loading = true;
        try {
          await this.submitImage();
        } catch (error) {
          console.log(error);
        }

        this.tagCode = row.tagCode;
        this.dialogUpdateImgVisible = true;
      } else {
        this.loading = true;
        const { content } = await getHouseInfo({ houDelId: this.houDelId });
        // 需要校验vr信息
        if (this.vrDownLoadCheck(content.hmDelSummaryInfo) === true) {
          try {
            await this.submitImage();
          } catch (error) {
            console.log(error);
          }
          this.tagCode = row.tagCode;
          this.dialogUpdateImgVisible = true;
        }
      }

      this.loading = false;
    },
    /** 关于vr是否下载的校验 */
    vrDownLoadCheck(row) {
      let state = row.houSubTypeState;
      let delId = row.delId;
      if (state == "1") {
        return this.$message.error("VR正在下载中，请等待VR下载完后使用～");
      }
      if (state == "-1" || state == "0") {
        let msg = state == "0" ? "该功能需要下载VR后方可使用，是否下载？" : "VR下载失败，是否重新下载？";
        return this.$messageBox.confirm(msg).then(() => {
          menuHandler
            .call(this, VR_COMPOUND_ADD)
            .then(() => {
              submitVrTask({
                delId,
              }).then((res) => {
                // 下载vr
                getMemberPower({
                  menuId: VR_COMPOUND_ADD,
                  agentId: this.sessionUser.id,
                });

                return this.$messageBox.confirm("vr房源下载中，需要3-5分钟", {
                  confirmButtonText: "我知道了",
                  showCancelButton: false,
                });
              });
            })
            .catch((error) => {});
        });
      }

      return true;
    },
    onMove({ relatedContext, draggedContext }) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      return (!relatedElement || !relatedElement.fixed) && !draggedElement.fixed;
    },

    handleMove(model) {
      // console.log(model);
      if (model.tagCode == "huxingtu") {
        let i = this.imageVO.houseTypeList.findIndex((item) => {
          return item.fileId == model.fileId;
        });
        let target = this.imageVO.houseTypeList.splice(i, 1)[0];
        target.tagCode = "";
        target.tagName = "未选择";
        target.selectAble = true;
        this.imageVO.indoorList.push(target);
      } else {
        let i = this.imageVO.indoorList.findIndex((item) => {
          return item.fileId == model.fileId;
        });
        let target = this.imageVO.indoorList.splice(i, 1)[0];
        target.tagCode = "huxingtu";
        target.tagName = "户型图";
        target.selectAble = false;
        this.imageVO.houseTypeList.push(target);
      }
    },

    handleRemoveImg(fileId) {
      for (let key in this.imageVO) {
        let i = this.imageVO[key].findIndex((v) => {
          return v.fileId == fileId;
        });
        if (i > -1) {
          let file = this.imageVO[key][i];
          this.uploadedImagesList = this.uploadedImagesList.filter(
            (item) => item.name != file.name || item.size != file.size,
          );

          this.imageVO[key].splice(i, 1);
          break;
        }
      }
    },
    handleModelUpdate(fileId, imgTag) {
      for (let key in this.imageVO) {
        let i = this.imageVO[key].findIndex((v) => {
          return v.fileId == fileId;
        });
        if (i > -1) {
          let newvo = Object.assign(this.imageVO[key][i], imgTag);
          this.imageVO[key].splice(i, 1, newvo);
          break;
        }
      }
    },
    beforeAvatarUpload({ maxlength, minWidth, minHeight }) {
      return (file) => {
        // console.log("上传图片", file);
        if (this.uploadedImagesList.find((item) => item.name == file.name && item.size == file.size)) {
          this.$message.error("上传的图片重复！");
          return false;
        }
        if (this.imageVO.houseTypeList.length >= maxlength) {
          this.handleExceed();
          return false;
        }
        const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
        if (!isJPG) {
          this.$message.error("上传图片只能是 image/jpeg/png 格式!");
          return false;
        }

        let _URL = window.URL || window.webkitURL;
        let src = _URL.createObjectURL(file);
        return measureImageInvalid(src, minWidth, minHeight).catch(() => {
          this.$message.error(`上传图片尺寸不合格`);
          return Promise.reject();
        });
      };
    },
    //上传成功返回
    handleSuccess({ key, maxlength, pixel, tagCode, tagName }) {
      const list = this.imageVO[key];
      return (res, file) => {
        // console.log("上传成功", { res, file });
        if (file.response.length <= 0) {
          return this.$message.error("图片上传失败");
        }
        if (list.length < maxlength) {
          this.$message.success("图片上传成功");
          let _item = { name: file.name, size: file.size };
          this.uploadedImagesList.push(_item);
          list.push({
            cover: 0,
            fileId: res[0].id,
            houDelId: this.houDelId,
            type: "pic",
            tagCode,
            tagName: tagName || "未选择",
            url: this.uploadImgUrl + res[0].id,
            fixed: false,
            invalid: false,
            ..._item,
            selectAble: !tagName,
          });
        } else {
          this.handleExceed();
        }
      };
    },
    handleExceed() {
      this.$message.error("该栏图片数量已达上限！");
    },
    submitImage() {
      let houImgList = [...this.imageVO.indoorList, ...this.imageVO.houseTypeList, ...this.imageVO.circumList];
      houImgList.forEach((item, index) => {
        item.cover = index;
      });

      return updateImage({ houImgList })
        .catch((error) => {
          this.$message.error("图片保存超时！");
          return Promise.reject();
        })
        .then(({ isSuccess, errorMessage = "" }) => {
          if (!isSuccess) {
            return this.$messageBox
              .confirm(`保存图片失败，${errorMessage}`, {
                confirmButtonText: "我知道了",
                showCancelButton: false,
              })
              .finally(() => {
                return Promise.reject();
              });
          }
        });
    },
  },
};
</script>

<style scoped>
.tips-first {
  background: rgb(255, 76, 75);
  color: white;
  padding: 0 10px;
  border-radius: 10px;
  margin: 0 20px;
  position: relative;
}
.tips-first::after {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid rgb(255, 76, 75);
  left: 50%;
  bottom: -5px;
  transform: translateX(-50%);
}
.list-group-item {
  cursor: move;
  display: inline-block;
}

.list-group-item i {
  cursor: pointer;
}
.flip-list-move {
  transition: transform 0.5s;
}
body >>> .options-wrap .cell {
  display: flex;
}
</style>
